package com.ece.friendly.service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ece.friendly.dao.ArticleDao;
import com.ece.friendly.model.Article;

@Service
public class ArticleServiceImp implements ArticleService{

	@Autowired
	private ArticleDao articleDao;
	

	@Override
	public List<Article> getAllArticle() {
		return articleDao.getAllArticle();
	}

	@Override
	public Article getArticle(int id) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public List<Article> getArticles(String login) {
		
		return articleDao.getArticles(login);
	}

	@Override
	public List<Article> getTopArticles(int limit) {
		return articleDao.getTopArticles(limit);
	}

	@Override
	public boolean addArticle(String login, String type_event, String nom,int etat, String conseil, float prix_jour, FileItem photo,long date,String dir) 
	{
		String path=dir+"images\\";
		File folder = new File(path+login);
		if(!folder.exists())
			folder.mkdirs();
		
		String pathArticle=path+login+"\\"+FilenameUtils.getName(photo.getName());
		
		File picture = new File(pathArticle);
		
		if(picture.exists()){
			pathArticle=FilenameUtils.removeExtension(pathArticle);
			pathArticle+=new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
			pathArticle+="."+photo.getName().split("\\.")[photo.getName().split("\\.").length-1];
		}
		
		
		try {
			picture=new File(pathArticle);
			picture.createNewFile();
			OutputStream out = new FileOutputStream(pathArticle);
			InputStream in=photo.getInputStream();
			ImageIO.write(ImageIO.read(in),"jpg",out );
			out.close();in.close();
			return articleDao.addArticle(login, type_event, nom, etat, conseil, prix_jour, "/friendly/images/"+login+"/"+picture.getName(),date);
			
		} catch (IOException e) {
			e.printStackTrace();return false;
		}
			
	}

	@Override
	public Article getArticle(String stylie, long date) {
		return articleDao.getArticle(stylie, date);
	}

	
}
